"""
FastAPI爬虫后端 - 主应用文件
支持Session和浏览器管理，用户可自由选择session和浏览器执行任务
"""

import asyncio
import uuid
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Any
from contextlib import asynccontextmanager

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel

from managers.session_manager import SessionManager
from managers.browser_manager import BrowserManager  
from managers.task_manager import TaskManager
from models.api_models import SessionInfo, BrowserInfo, TaskRequest, TaskResult


# 全局管理器实例
session_manager = SessionManager()
browser_manager = BrowserManager()
task_manager = TaskManager(session_manager, browser_manager)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时
    print("🚀 FastAPI爬虫后端启动")
    
    # 创建一些默认Session
    for i in range(3):
        session_manager.create_session()
    
    # 创建一个默认浏览器
    await browser_manager.create_browser("Default Browser")
    
    yield
    
    # 关闭时
    print("🔄 正在关闭所有浏览器...")
    await browser_manager.cleanup_all_browsers()
    print("✅ FastAPI爬虫后端关闭完成")


# 创建FastAPI应用
app = FastAPI(
    title="爬虫管理后端",
    description="支持Session和浏览器管理的爬虫系统",
    version="1.0.0",
    lifespan=lifespan
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# ==================== API 路由 ====================

@app.get("/")
async def root():
    """根路径"""
    return {
        "message": "FastAPI爬虫后端运行中",
        "sessions": len(session_manager.sessions),
        "browsers": len(browser_manager.browsers),
        "tasks": len(task_manager.tasks)
    }


# Session管理API
@app.get("/sessions", response_model=List[SessionInfo])
async def get_sessions():
    """获取所有Session"""
    return session_manager.get_all_sessions()


@app.get("/sessions/usable", response_model=List[SessionInfo])
async def get_usable_sessions():
    """获取可用的Session"""
    return session_manager.get_usable_sessions()


@app.post("/sessions", response_model=SessionInfo)
async def create_session(max_usage_count: int = 50, max_age_hours: int = 2):
    """创建新Session"""
    session = session_manager.create_session(max_usage_count, max_age_hours)
    return session_manager._session_to_info(session)


@app.get("/sessions/{session_id}", response_model=SessionInfo)
async def get_session(session_id: str):
    """获取指定Session"""
    session = session_manager.get_session(session_id)
    if not session:
        raise HTTPException(status_code=404, detail="Session not found")
    return session_manager._session_to_info(session)


@app.delete("/sessions/{session_id}")
async def delete_session(session_id: str):
    """删除Session"""
    if session_manager.delete_session(session_id):
        return {"message": f"Session {session_id} deleted"}
    raise HTTPException(status_code=404, detail="Session not found")


@app.post("/sessions/cleanup")
async def cleanup_sessions():
    """清理过期Session"""
    count = session_manager.cleanup_expired_sessions()
    return {"message": f"Cleaned up {count} expired sessions"}


# 浏览器管理API
@app.get("/browsers", response_model=List[BrowserInfo])
async def get_browsers():
    """获取所有浏览器"""
    return browser_manager.get_all_browsers()


@app.post("/browsers", response_model=BrowserInfo)
async def create_browser(
    name: Optional[str] = None,
    proxy_url: Optional[str] = None,
    headless: bool = True
):
    """创建新浏览器"""
    browser_id = await browser_manager.create_browser(name, proxy_url, headless)
    browser_data = browser_manager.get_browser(browser_id)
    return browser_manager._browser_to_info(browser_data)


@app.get("/browsers/{browser_id}", response_model=BrowserInfo)
async def get_browser(browser_id: str):
    """获取指定浏览器"""
    browser_data = browser_manager.get_browser(browser_id)
    if not browser_data:
        raise HTTPException(status_code=404, detail="Browser not found")
    return browser_manager._browser_to_info(browser_data)


@app.delete("/browsers/{browser_id}")
async def close_browser(browser_id: str):
    """关闭浏览器"""
    if await browser_manager.close_browser(browser_id):
        return {"message": f"Browser {browser_id} closed"}
    raise HTTPException(status_code=404, detail="Browser not found")


# 任务管理API
@app.post("/tasks", response_model=Dict[str, str])
async def create_task(task_request: TaskRequest):
    """创建新任务"""
    task_id = await task_manager.execute_task(task_request)
    return {"task_id": task_id, "status": "created"}


@app.get("/tasks", response_model=List[TaskResult])
async def get_tasks():
    """获取所有任务"""
    return task_manager.get_all_tasks()


@app.get("/tasks/running")
async def get_running_tasks():
    """获取运行中的任务"""
    return {"running_tasks": task_manager.get_running_tasks()}


@app.get("/tasks/{task_id}", response_model=TaskResult)
async def get_task(task_id: str):
    """获取任务结果"""
    task = task_manager.get_task(task_id)
    if not task:
        raise HTTPException(status_code=404, detail="Task not found")
    return task


# 健康检查API
@app.get("/health")
async def health_check():
    """健康检查"""
    return {
        "status": "healthy",
        "timestamp": datetime.now().isoformat(),
        "sessions": {
            "total": len(session_manager.sessions),
            "usable": len(session_manager.get_usable_sessions())
        },
        "browsers": {
            "total": len(browser_manager.browsers),
            "active": len([b for b in browser_manager.browsers.values() if b["is_active"]])
        },
        "tasks": {
            "total": len(task_manager.tasks),
            "running": len(task_manager.running_tasks)
        }
    }


if __name__ == "__main__":
    import uvicorn
    
    print("🚀 启动FastAPI爬虫后端...")
    print("📝 API文档: http://localhost:8000/docs")
    print("🔍 健康检查: http://localhost:8000/health")
    
    uvicorn.run(
        "app:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
        log_level="info"
    ) 